//
//  BanBu_NavigationController.m
//  BanBu
//
//  Created by jie zheng on 12-7-5.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#define KEY_WINDOW  [[UIApplication sharedApplication]keyWindow]

#import "BanBu_NavigationController.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_NavButton.h"
@interface BanBu_NavigationController ()
{
    CGPoint startTouch;
    
    UIImageView *lastScreenShotView;
    UIView *blackMask;
}

@property (nonatomic,retain) UIView *backgroundView;
@property(nonatomic, retain)NSMutableArray *screenShotsList;
@property (nonatomic,assign) BOOL isMoving;

@end

@implementation BanBu_NavigationController

@synthesize isLoading;

//替换返回按钮

- (void)popself {
    
    //    if (isLoading) {
    //        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"上次的操作还没结束！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    //        [alert show];
    //        [alert release];
    //        return;
    //
    //    }
    
    [self popViewControllerAnimated:YES];
    
    
    
    
}
-(void)viewWillLayoutSubviews
{
    if(IS_IOS_7)
    {
        self.view.frame = CGRectMake(0, 0, __MainScreen_Width,__MainScreen_Height+20);
    }
}
- (id)initWithRootViewController:(UIViewController *)rootViewController
{
    self = [super initWithRootViewController:rootViewController];
    
    
    if(self)
    {
        
        if ([self.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
        {
            
            [self changeTheme1];
//            self.screenShotsList = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
//            self.canDragBack = YES;
//            
//            [self.navigationBar setTintColor:[UIColor whiteColor]];
            
            NSMutableDictionary *barAttrs = [NSMutableDictionary dictionary];
            [barAttrs setObject:[UIColor whiteColor] forKey:UITextAttributeTextColor];
            [barAttrs setObject:[NSValue valueWithUIOffset:UIOffsetMake(0, 0)] forKey:UITextAttributeTextShadowOffset];
            [self.navigationBar setTitleTextAttributes:barAttrs];
            
//            self.navigationController.navigationBar.translucent = NO; //让状态栏和导航栏不透明

            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTheme1) name:kThemeDidChangeNotification object:nil];
        }
        
        return self;
    }
    
    return nil;
}
//-(void)viewDidLoad
//{
//    [super viewDidLoad];
//    
//    UIImageView *shadowImageView = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"leftside_shadow_bg.png"]]autorelease];
//    shadowImageView.frame = CGRectMake(-10, 0, 10, self.view.frame.size.height);
//    [self.view addSubview:shadowImageView];
//    
//    UIPanGestureRecognizer *recognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(paningGestureReceive:)] autorelease];
//    [recognizer delaysTouchesBegan];
//    [self.view addGestureRecognizer:recognizer];
//}

-(void)changeTheme1 
{
//    UIImage *backImage = [ThemeManager getThemeImage:@"table_backimage.jpg"];
//    if(backImage)
//        self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
//    else
//        self.view.backgroundColor = [UIColor colorWithRed:1 green:249.0/255.0 blue:236.0/255 alpha:1];
//   

    NSString *navImageName = nil;
    if(IS_IOS_7)
    {
        navImageName = @"topbar_ios7.png";
    }
    else
        navImageName = @"topbar.png"; //高度44px
//    [self.navigationBar setBarStyle:UIBarStyleBlackTranslucent];//不设背景图这设置这个将获得毛玻璃效果
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:navImageName] forBarMetrics:UIBarMetricsDefault];
    [self.navigationBar setBackgroundImage:[ThemeManager getThemeImage:navImageName] forBarMetrics:UIBarMetricsDefault];
}



- (UIBarButtonItem*)createBackButton
{
    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
    btn_return.position = ButtonPositionLeft;
    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
//    btn_return.titleLabel.font = [UIFont systemFontOfSize:15];

    UIBarButtonItem *bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
    [btn_return release];
    return bar_itemreturn;

}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
//    [self.screenShotsList addObject:[self capture]];

    if(IS_IOS_7)
    {
        viewController.edgesForExtendedLayout = UIRectEdgeNone;
        viewController.extendedLayoutIncludesOpaqueBars = NO;
        viewController.modalPresentationCapturesStatusBarAppearance = NO;
        viewController.automaticallyAdjustsScrollViewInsets = NO;
    }

    [super pushViewController:viewController animated:animated];
    if(viewController.navigationItem.hidesBackButton)
        return;
    if (viewController.navigationItem.leftBarButtonItem== nil && [self.viewControllers count] > 1) {
        
        viewController.navigationItem.leftBarButtonItem =[self createBackButton];
    }
    
}
//
//-(UIImage *)capture
//{
//    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
//    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return img;
//}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    return [super popViewControllerAnimated:animated];
}
// set lastScreenShotView 's position and alpha when paning
//- (void)moveViewWithX:(float)x
//{
//    
//    x = x>320?320:x;
//    x = x<0?0:x;
//    
//    CGRect frame = self.view.frame;
//    frame.origin.x = x;
//    self.view.frame = frame;
//    
//    float scale = (x/6400)+0.95;
//    float alpha = 0.4 - (x/800);
//    NSLog(@"Move to:%f %f %f",x,scale,alpha);
//    
//    lastScreenShotView.transform = CGAffineTransformMakeScale(scale, scale);
//    blackMask.alpha = alpha;
//    
//}
//#pragma mark - Gesture Recognizer -
//
//- (void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
//{
//    // If the viewControllers has only one vc or disable the interaction, then return.
//    if (self.viewControllers.count <= 1 || !self.canDragBack) return;
//    
//    // we get the touch position by the window's coordinate
//    CGPoint touchPoint = [recoginzer locationInView:KEY_WINDOW];
//    
//    // begin paning, show the backgroundView(last screenshot),if not exist, create it.
//    if (recoginzer.state == UIGestureRecognizerStateBegan)
//    {
//        
//        _isMoving = YES;
//        startTouch = touchPoint;
//        
//        if (!self.backgroundView)
//        {
//            CGRect frame = self.view.frame;
//            
//            self.backgroundView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)]autorelease];
//            self.backgroundView.backgroundColor = [UIColor blackColor];
//            [self.view.superview insertSubview:self.backgroundView belowSubview:self.view];
//            
//            blackMask = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)]autorelease];
//            blackMask.backgroundColor = [UIColor blackColor];
//            [self.backgroundView addSubview:blackMask];
//        }
//        
//        self.backgroundView.hidden = NO;
//        
//        if (lastScreenShotView) [lastScreenShotView removeFromSuperview];
//        
//        UIImage *lastScreenShot = [self.screenShotsList lastObject];
//        lastScreenShotView = [[[UIImageView alloc]initWithImage:lastScreenShot]autorelease];
//        [self.backgroundView insertSubview:lastScreenShotView belowSubview:blackMask];
//        
//        //End paning, always check that if it should move right or move left automatically
//    }
//    else if (recoginzer.state == UIGestureRecognizerStateEnded){
//        
//        if (touchPoint.x - startTouch.x > 50)
//        {
//            [UIView animateWithDuration:0.3 animations:^{
//                [self moveViewWithX:320];
//            } completion:^(BOOL finished) {
//                
//                [self popViewControllerAnimated:NO];
//                CGRect frame = self.view.frame;
//                frame.origin.x = 0;
//                self.view.frame = frame;
//                
//                _isMoving = NO;
//            }];
//        }
//        else
//        {
//            [UIView animateWithDuration:0.3 animations:^{
//                [self moveViewWithX:0];
//            } completion:^(BOOL finished) {
//                _isMoving = NO;
//                self.backgroundView.hidden = YES;
//            }];
//            
//        }
//        return;
//        
//        // cancal panning, alway move to left side automatically
//    }else if (recoginzer.state == UIGestureRecognizerStateCancelled){
//        
//        [UIView animateWithDuration:0.3 animations:^{
//            [self moveViewWithX:0];
//        } completion:^(BOOL finished) {
//            _isMoving = NO;
//            self.backgroundView.hidden = YES;
//        }];
//        
//        return;
//    }
//    
//    // it keeps move with touch
//    if (_isMoving) {
//        [self moveViewWithX:touchPoint.x - startTouch.x];
//    }
//}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kThemeDidChangeNotification object:nil];
    [super dealloc];
//    [_screenShotsList release],_screenShotsList = nil;
}
@end